package com.cloudeasy.user.service.expand;

import com.cloudeasy.api.enums.ResultCodeEnum;
import com.cloudeasy.api.exception.CloudEasyException;
import com.cloudeasy.api.util.BPwdEncoderUtil;
import com.cloudeasy.api.vo.oauth.JWT;
import com.cloudeasy.user.client.ServerClient;
import com.cloudeasy.user.dto.LoginDTO;
import com.cloudeasy.user.po.User;
import com.cloudeasy.user.service.UserInfoService;
import com.cloudeasy.user.service.UserService;
import org.springframework.stereotype.Service;

@Service
public class UserDetailService {

    private final ServerClient serverClient;

    private final UserService userService;

    private final UserInfoService userInfoService;

    public UserDetailService(ServerClient serverClient, UserService userService, UserInfoService userInfoService) {
        this.serverClient = serverClient;
        this.userService = userService;
        this.userInfoService = userInfoService;
    }

    /**
     * 登录
     *
     * @param loginDTO {@link LoginDTO}登录信息
     * @return {@link JWT}
     */
    public JWT login(LoginDTO loginDTO) {
        // 查询数据库
        User user = userService.getByAccount(loginDTO.getAccount());
        if (user == null) {
            throw new CloudEasyException(ResultCodeEnum.ACCOUNT_NOT_EXISTS);
        }

        if (!user.getUnlocked()) {
            throw new CloudEasyException(ResultCodeEnum.ACCOUNT_LOCKED);
        }

        if (!BPwdEncoderUtil.matches(loginDTO.getPassword(), user.getPassword())) {
            throw new CloudEasyException(ResultCodeEnum.LOGIN_FAILED);
        }

        // 获取JWT
        JWT jwt = serverClient.getToken("Basic Y2xvdWRlYXN5OmNsb3VkZWFzeS1zZWNyZXQ=", "password", loginDTO.getAccount(), loginDTO.getPassword());
        if (jwt == null) {
            throw new CloudEasyException(ResultCodeEnum.REMOTE_ERROR);
        }

        userInfoService.login(user.getId());

        return jwt;
    }
}
